package com.shopcart.servlet;

import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shopcart.controller.ItemController;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public AdminServlet() {
		super();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
			IOException {
		ItemController ic = null;
		try {
			Context ctx = new InitialContext();
			ic = (ItemController) ctx.lookup("ejb/ItemControllerBean");
		} catch (NamingException e) {
			System.err.println("Error getting bean!");
			e.printStackTrace();
		}

		if (request.getQueryString().equals("addProduct")) {
			String productName = request.getParameter("productName");
			int productCount = Integer.parseInt(request.getParameter("productCount"));

			ic.saveProduct(productName, productCount);
		} else if (request.getQueryString().equals("updateProduct")) {
			Long productId = Long.valueOf(request.getParameter("product"));
			int productCount = Integer.parseInt(request.getParameter("productCount"));
			
			ic.updateProduct(productId, productCount);
		} else if (request.getQueryString().equals("addMatchingProducts")) {
			String product1 = request.getParameter("product1");
			String product2 = request.getParameter("product2");
			
			if (!product1.equals(product2)) {
				ic.matchProducts(product1, product2);
			}
		} else if (request.getQueryString().equals("removeMatchingProducts")) {
			String product1 = request.getParameter("product1");
			String product2 = request.getParameter("product2");
			
			if (!product1.equals(product2)) {
				ic.unmatchProducts(product1, product2);
			}
		}
		
		request.getRequestDispatcher("admin.jsp").forward(request,response);
	}
}